﻿@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutChild.cshtml";
}
<style type="text/css">
    table, table td, table th
    {
        border-collapse: collapse;
        font-size: 12px;
    }
    table
    {
        table-layout: fixed;
    }
    td
    {
        white-space: nowrap;
        display: table-cell;
        vertical-align: inherit;
    }
    .uploadify
    {margin-top:4px;
     padding-top:3px;
     padding-bottom:0px;
     margin-bottom:0px;
     border: #ccc 1px solid;}
 .uploadify-button
        {
            background-color: transparent;
            border: none;
            padding: 0;
        }
        .uploadify:hover .uploadify-button
        {
            background-color: transparent;
            border: none;
            padding: 0;
            margin-top:-6px;
        }
        .uploadbtn
        {

            width: 40px;
            height: 20px;
            background-color: transparent;
            border: none;
            padding: 0;
        }
        .uploadify-queue
        {
            
             left:1px;
             top:1px;
             width:40px;
        }  
</style>
@section head {
    @if (false)
    {
        <script src="/Scripts/jquery-1.6.4-vsdoc.js" type="text/javascript"></script>
    }
    <script src="/Scripts/grid.js" type="text/javascript"></script>
    <script type="text/javascript"
     src="@Url.Content("~/Scripts/jquery.uploadify-3.1.js")"  ></script>
    <link href="@Url.Content("~/Content/uploadify/uploadify.css")"     rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        var oldtd = null;
        var ispaste = false; //是否粘贴
        var reportstate = "";
        var isentersave = false; //用来指示是否敲回车键
        $(document).ready(function () {

            getReportInfo(); //得到报表属性信息
            initUpload();
            $("body").append("<input id='txt' type='text' style='position:absolute; left:-1000px;top:-1000px; border:0px; z-index:10;font-size:12px; background:#ffff33;' value=''/>");
            $("#txt").hide();
            reportstate = $("#state").val();

            $("#TableMain").css("left", ($(document).width() - $("#TableMain").width()) / 2>=0?($(document).width() - $("#TableMain").width()) / 2:0 ).show();
            //绑定回车事件
            $(document).keydown(function (e) {
                var key = (e.keyCode) || (e.which) || (e.charCode); //兼容浏览器                   
                if (key == 13) {
                    isentersave = true;
                    saveData(oldtd);
                }
            });
            //绑定tablemain所在的父div的滚动事件
            $("#TableMain").parent().scroll(function () {
                saveData(oldtd);
                $("#txt").hide();
            });
            //绑定单元格单击事件
            if (reportstate == "0") {//如果编辑状态是0此时可以编辑,其他任何状态都不能编辑 
                $("#TableMain td").mousedown(function () {
                    isentersave = false;
                    if ($(this).attr("isEdit") == "0") return;
                    if (oldtd != null && !ispaste) {//如果执行过粘贴，第一次点击时不执行此处
                        saveData(oldtd);
                    }
                    $(this).css("background-color", "");
                    var digits = $(this).attr("digits");
                    ispaste = false;
                    var offset = $(this).offset();
                    $("#txt").css("left", offset.left + 2);
                    $("#txt").css("top", offset.top + 1);
                    $("#txt").css("width", $(this).width()).css("height", $(this).height());
                    $("#txt").val($(this).html());
                    oldtd = $(this);
                    //输入框值类型判定
                    if (digits) {
                        $("#txt").keypress(checkNumber);
                        $("#txt").attr("digits", digits);
                    }
                    $("#txt").show();
                    //有时focus不起作用，可以用setTimeout 延迟一会，这样可以解决这个问题
                    window.setTimeout(function () { document.getElementById("txt").focus(); }, 100);
                })
            }
            if ('@ViewBag.CheckData' == '1') { checkDataOnly(); }

            //如果报表不是可编辑状态，不能导入数据。
            if (reportstate != "0") {
                $("#btnImport").css('display', 'none');
                $("#checkData").css('display', 'none');
                $("#calcFormulatCell").css('display', 'none');
            }
        });

        function saveData(nowtd) {
            if ($("#txt").css("display") != "none") {
                var _val = nowtd.html();
                var _inputVal = $.trim($("#txt").val());
                var digits = nowtd.attr("digits");
                if (digits) {
                    try {
                        _inputVal = formatNumber(_inputVal, digits);
                    } catch (e) {
                        _inputVal = "";
                    }
                    if (_inputVal == 0) _inputVal = "";
                }
                if (_inputVal == _val || reportstate != "0") {//如果修改前和修改后的值一样或是报表不可修改，则直接跳下格。不用保存。
                    if (isentersave)//判断是否回车键保存，如果是的话自动跳到下一单元格
                        nextTd(nowtd);
                }
                else {
                    var _oldVal = oldtd.html();
                    oldtd.html(_inputVal);
                    _val = _inputVal;
                    var zbbh = nowtd.attr("zb");
                    var result = $("#formdetail").serialize();
                    $.ajax({
                        type: "POST",
                        url: "/DataManage/Report/Save",
                        data: result + "&zbbh=" + zbbh + "&val=" + _val,
                        success: function (msg) {
                            if (msg == "-1") {
                                alert('不能修改非单位的数据');
                                return;
                            }
                            if (msg != "1")
                                alert("保存失败!");
                            else {
                                if (isentersave)//判断是否回车键保存，如果是的话自动跳到下一单元格
                                    nextTd(nowtd);
                            }
                        }
                    });
                }
            }
        }

        function nextTd(nowtd) {
            var td = GetNextTdObject(nowtd);
            if (td == null) return;
            var trIndex = td.parent().index();
            var tdIndex = td.index();
            var offset = td.offset();
            $("#txt").css("left", offset.left + 2);
            $("#txt").css("top", offset.top + 1);
            $("#txt").css("width", td.width()).css("height", td.height());
            $("#txt").val(td.html());
            oldtd = td;
            $("#txt").show();
            //有时focus不起作用，可以用setTimeout 延迟一会，这样可以解决这个问题
            window.setTimeout(function () { document.getElementById("txt").focus(); }, 100);
        }

        function GetNextTdObject(nowtd) {
            var trIndex = nowtd.parent().index();
            var tdIndex = nowtd.index();
            nowtd = $("tr:eq(" + trIndex + ")").children("td:eq(" + (tdIndex + 1) + ")"); //判断是否是一行中最后一个单元格,如果是的话则跳转到下一行。
            if (nowtd.index() < 0) {
                nowtd = $("tr:eq(" + (trIndex + 1) + ")").children("td:eq(0)");
            }
            //如果最后一格是不可编辑的，将造成死循环。
            if (nowtd.parent().index() < 0) {
                // nowtd = $("tr:eq(" + (trIndex - 1) + ")").children("td").last();
                //                nowtd = getLastEditAbledtd();
                return;

            }
            if (nowtd.attr("isEdit") == "1") {
                return nowtd;
            }
            else {
                return GetNextTdObject(nowtd);
            }
        }
        //取得最后一个可编辑的单元格。
        function getLastEditAbledtd() {
            
            var lastedittd;
            $("td").each(function (i, td) {
                if ($(td).attr("isEdit") == "1") {
                    if (lastedittd == null || lastedittd == "")//找到第一个单元格后，就不要再给lastedittd赋值了。因为each无法直接用break跳出
                        lastedittd = $(td);
                    //如果到了最后一格后，敲回车，让其回到第一个可以录入的单元格。
                }
            });
            return lastedittd;
        }

        function getReportInfo() {
            var cycle = $("#cycle").val();
            var year = $("#year").val();
            var month = $("#month").val();
            var day = $("#day").val();
            $("#titlediv").html("单位:" + '@ViewBag.OrganizeName' + " 周期属性:" + GetCycleName(cycle) + "&nbsp;&nbsp;&nbsp;报表期间:" + DateTimeStr(cycle, year, month, day) + " 报表ID:" + '@ViewBag.SubmitInfoId' + "&nbsp;&nbsp;&nbsp;报表状态:<span style='color:red'>" + ($("#state").val() == "0" ? "可编辑" : "只读") + "</span>");
        }

        //获取剪切板数据 函数  
        function getClipboard() {
            if (window.clipboardData) {
                return (window.clipboardData.getData('Text'));
            }
            else if (window.netscape) {
                netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                var clip = Components.classes['mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return;
                var trans = Components.classes['mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return;
                trans.addDataFlavor('text/unicode');
                clip.getData(trans, clip.kGlobalClipboard);
                var str = new Object();
                var len = new Object();
                try {
                    trans.getTransferData('text/unicode', str, len);
                }
                catch (error) {
                    return null;
                }
                if (str) {
                    if (Components.interfaces.nsISupportsWString) strstr = str.value.QueryInterface(Components.interfaces.nsISupportsWString);
                    else if (Components.interfaces.nsISupportsString) strstr = str.value.QueryInterface(Components.interfaces.nsISupportsString);
                    else str = null;
                }
                if (str) {
                    return (str.data.substring(0, len.value / 2));
                }
            }
            return null;
        }

        //读取剪切板数据，并将剪切板数据存放于各table cell中  
        function readClipboardData() {
            ispaste = true;
            var str = getClipboard(); //获取剪切板数据
            $("#txt").hide();
            var len = str.split("\n"); //获取行数  
            var tdIndex = oldtd.index(); //获取当前text控件的父元素td的索引  
            var trIndex = oldtd.parent().index(); //获取当前text控件的父元素的父元素tr的索引  
            var trStr;
            //从excle表格中复制的数据，最后一行为空行，因此无需对len数组中最后的元素进行处理  
            for (var i = 0; i < len.length - 1; i++) {
                //excel表格同一行的多个cell是以空格 分割的，此处以空格为单位对字符串做 拆分操作。。  
                trStr = len[i].split(/\s+/); //如果使用'\t'可以保留哪些为空的单元格，使用正则表达式则去除为空的单元格/\s+/
                for (var j = 0; j <= trStr.length - 1; j++) { //将excel中的一行数据存放在table中的一行cell中  
                    $("tr:eq(" + trIndex + ")").children("td:eq(" + (tdIndex + j) + ")").html(trStr[j]);
                }
                trIndex++;
            }
            return false; //防止onpaste事件起泡  
        }

        function calcFormulatCell() {
            parent.$.cover(true);
            $.post('/DataManage/Report/CalcFormulaZB', { submitInfoId: '@ViewBag.SubmitInfoId' }, function (d) {
                if (d.Success) {
                    var _href = window.location.href;
                    if (_href.lastIndexOf('?') > -1) {
                        _href = _href.substring(0, _href.lastIndexOf('?'));
                    }
                    window.location.href = _href;
                }
                parent.$.cover(false);
            })
        }

        function checkNumber() {
            return (event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 46 || event.keyCode == 45;
        }

        function exportReport() {
            var postData = $("#formdetail").serialize();
            window.location.href = '/DataManage/Report/ExportReport/?SubmitInfoId=' + '@ViewBag.SubmitInfoId';
        }

        function checkDataOnly() {
            $.post('/DataManage/Report/CheckDataLogic', { submitInfoId: '@ViewBag.SubmitInfoId' }, function (_data) {
                if (_data.ErrorMessage) {
                    top.asyncbox.alert(_data.ErrorMessage, '提示');
                    return;
                }
                if (_data.ErrorZBList.length > 0) {
                    for (var i = 0; i < _data.ErrorZBList.length; i++) {
                        $("td[row=" + _data.ErrorZBList[i].Key + "][col=" + _data.ErrorZBList[i].Value + "]").css("background-color", "Red");
                    }
                    var msg = '';
                    for (var i = 0; i < _data.ErrMsgList.length; i++) {
                        msg = msg + _data.ErrMsgList[i] + "<br/>";
                    }
                    top.asyncbox.alert(msg, '提示');
                }
                else {
                    top.asyncbox.alert('数据录入正确！', '提示');
                }
            });
        }


        function checkData(flag) {
            parent.$.cover(true);
            $.post('/DataManage/Report/CalcFormulaZB', { submitInfoId: '@ViewBag.SubmitInfoId' }, function (d) {
                parent.$.cover(false);
                if (d.Success) {
                    var _href = window.location.href;
                    if (_href.lastIndexOf('?') > -1) {
                        _href = _href.substring(0, _href.lastIndexOf('?'));
                    }
                    window.location.href = _href + "?checkdata=1";
                }
            })
        }

//        function importReport() {
//            if (!confirm('警告：导入数据会清除之前存在的数据，确定继续吗？')) return;
//           
//        }

        function initUpload() {
            $("#btnImport").uploadify({
                'formData': { 'ASPSESSID': '@(Session.SessionID)', 'AUTHID': '@ViewBag.auth', GUID: '@ViewBag.GUID', 'submitInfoId': '@ViewBag.SubmitInfoId' },
                'multi': false,
                'auto': true,
                'swf': '/Content/uploadify/uploadify.swf',
                'uploader': '/DataManage/Report/importReport',
                'width': 60,
                'fileTypeExts': '*.xls',
                'height': 22,
                'buttonImage': '/Content/import.png',
                'onSelect': function (e, queueId, fileObj) { parent.$.cover(true); }, //选择文件后触发的事件。
                'onUploadSuccess': function (file, data, response) {
                    parent.$.cover(false);
                    if (data == null || data.length == 0) {
                        var _href = window.location.href;
                        if (_href.lastIndexOf('?') > -1) {
                            _href = _href.substring(0, _href.lastIndexOf('?'));
                        }
                        window.location.href = _href;
                        top.asyncbox.tips('导入数据成功!', 'success');
                    }
                    else
                        top.asyncbox.alert('导入数据失败,失败原因：' + data, '提示');
                }
            });
        }
    </script>
}
<!--头部导航,不用时可以去掉-->
<div class="ui-layout-north" id='toolbar'>
    <div id="titlediv" class="headertitle">
   
    </div>
   

    <div style="float: right; margin-right: 20px; margin-top: 2px; line-height: 32px;">
        
    <div style="float: left;">
     <input type="file" name="btnImport" id="btnImport" class=" padding-top: 10px;"/>
    </div>
    <div style="float: right;">
    <!--<a onclick="importReport();" class="button green" id="importReport"><span class="icon-botton" style="background: url('/Content/16/import.png') no-repeat scroll 0px 4px;">
        </span>导入</a>&nbsp; -->
        <a onclick="exportReport();" class="button green" id="exportReport"><span class="icon-botton" style="background: url('/Content/16/export.png') no-repeat scroll 0px 4px;">
        </span>导出</a>&nbsp; 
        <a onclick="checkData();" class="button green" id="checkData"><span class="icon-botton" style="background: url('/Content/16/application_form_magnify.png') no-repeat scroll 0px 4px;">
        </span>校验</a> &nbsp;
         <a onclick="calcFormulatCell()" class="button green" id="calcFormulatCell"><span class="icon-botton" style="background: url('/Content/16/hj.png') no-repeat scroll 0px 4px;">
         </span>合计</a></div>
          
    </div>
</div>
<!--主窗体，页面都需要的div-->
<div class="ui-layout-center" style="overflow: auto;background: url(/Content/images/bj.gif) repeat;">
    @Html.Raw(ViewBag.H)
</div>
